<template>
  <div class="container pa">
    <div class="content wh pr" v-if="loginName">
      <!-- <div class="console">{{ testData }}</div> -->
      <header class="w">
        <p>简单聊天室</p>
        <p>{{ `登录名：${loginName}` }}</p>
      </header>
      <main ref="main">
        <div ref="messageList">
          <div
            class="message-row pr"
            :class="[item.loginName === loginName ? 'right' : 'left']"
            v-for="(item, index) in messageList"
            :key="index"
          >
            <div class="login-name pa">{{ item.loginName }}</div>
            <div class="avator pa">
              <img
                v-if="item.loginSex == 1"
                src="../assets/images/avator_male.png"
                alt=""
              />
              <img v-else src="../assets/images/avator_female.png" alt="" />
            </div>
            <div class="msg-box">
              <div class="msg-content">{{ item.msg }}</div>
            </div>
          </div>
        </div>
      </main>
      <footer>
        <el-input
          type="textarea"
          :rows="4"
          resize="none"
          v-model="msg"
        ></el-input>
        <el-button
          class="btn-send"
          :disabled="!msg"
          type="primary"
          @click="sendMsg"
          >发送</el-button
        >
      </footer>
    </div>
    <DialogLogin
      v-model:visible="loginVisible"
      @getLoginInfo="getLoginInfo"
      v-else
    />
  </div>
</template>

<script>
import DialogLogin from './DialogLogin.vue'
export default {
  name: 'Chat',
  components: { DialogLogin },
  data() {
    return {
      msg: '',
      websock: null,
      loginVisible: true,
      loginName: '',
      loginSex: 0,
      messageList: [],
      loginNameList: [],
      testData: null,
    }
  },
  created() {
    if (this.isLogin()) {
      this.initWebSocket()
    }
  },
  computed: {
    currentLoginList() {
      return this.loginNameList
    },
  },
  beforeUnmount() {
    this.websocketclose()
  },
  methods: {
    initWebSocket() {
      //初始化weosocket
      //   const host = '192.168.0.109'
      const host = '47.107.250.55'
      const port = 39010
      const wsuri = `ws://${host}:${port}`
      this.websock = new WebSocket(wsuri)
      this.testData = JSON.stringify(this.websock)
      this.websock.onmessage = this.websocketonmessage
      this.websock.onopen = this.websocketonopen
      this.websock.onerror = this.websocketonerror
      this.websock.onclose = this.websocketclose
    },
    // 在open时，注册登录人信息
    websocketonopen() {
      //连接建立之后执行send方法发送数据
      let actions = { loginName: this.loginName, loginSex: this.loginSex }
      this.websocketsend(JSON.stringify(actions))
    },
    websocketonerror() {
      //连接建立失败重连
      //   this.initWebSocket()
      this.testData = '连接建立失败'
      //   this.websocketclose()
    },
    websocketonmessage(e) {
      //数据接收
      this.testData = 'websocketonmessage'
      this.getData(e.data)
    },
    // websocket 的send方法自带参数
    websocketsend(data) {
      this.testData = 'websocketsend'
      this.websock.send(data)
    },
    websocketclose(e) {
      //关闭
      this.testData = 'websocketclose'
      console.log('断开连接', e)
    },
    // 点击发送按钮发送数据
    sendMsg() {
      const that = this
      const msgData = {
        loginName: that.loginName,
        loginSex: that.loginSex,
        msg: that.msg,
      }
      this.websocketsend(JSON.stringify(msgData))
      this.msg = ''
    },
    // 通过登陆弹窗设置登陆人信息
    getLoginInfo(val) {
      this.loginName = val.loginName
      this.loginSex = val.loginSex
      this.initWebSocket()
    },
    // 通过sessionStorage判断是否登录
    isLogin() {
      let name = sessionStorage.getItem('loginName')
      let sex = sessionStorage.getItem('loginSex')
      console.log('isLogin', sex)
      if (name) {
        this.loginName = name
        this.loginSex = sex
        this.loginVisible = false
      }
      return !!name
    },
    // 接收服务端数据
    getData(serverData) {
      const data = JSON.parse(serverData)
      const res = data.res
      let loginName = data.loginName || ''
      let loginSex = data.loginSex || ''
      let msg = ''
      this.loginNameList = data.loginNameList.split(',') || []
      if (res.msg) {
        msg = res.msg
        this.messageList.push({
          loginName,
          loginSex,
          msg,
        })
        this.scrollToDown()
      }
      console.log('接收服务端数据--data', data)
      console.log('接收服务端数据--res', res)
      console.log('接收服务端数据--messageList', this.messageList)
    },
    // 聊天页面滚动到底部
    scrollToDown() {
      const { main, messageList } = this.$refs
      this.$nextTick(() => {
        main.scrollTop = messageList.offsetHeight
      })
    },
  },
}
</script>

<style scoped lang="scss">
@import '@/assets/styles/variable.scss';
.container {
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: px2(600);
  height: px2(800);
  box-shadow: 0 px2(5) px2(30) px2(5) rgba(0, 0, 0, 0.3);
  overflow: hidden;
  .console {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    min-height: px2(200);
    font-size: px2(14);
    color: #fff;
    background-color: rgba(0, 0, 0, 0.5);
  }
  .content {
    display: flex;
    flex-direction: column;
  }
  header {
    height: px2(80);
    line-height: px2(40);
    text-align: center;
    font-size: px2(20);
    border-bottom: px2(2) solid #ededed;
    p {
      &:first-child {
        font-weight: bold;
      }
    }
  }
  main {
    padding: px2(20);
    flex: 1;
    background-color: #f5f5f5;
    overflow-y: auto;
  }
  footer {
    width: 100%;
    padding: px2(10);
    background-color: #ededed;
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    .btn-send {
      margin: px2(10) 0 0 0;
    }
  }
  .message-row {
    $paddingLR: px2(50);
    $paddingT: px2(40);
    width: 100%;
    display: flex;
    padding: px2(40) $paddingLR 0;
    &:nth-child(n + 2) {
      margin-top: px2(24);
    }
    &.left {
      .login-name,
      .avator {
        left: 0;
      }
      .msg-box {
        justify-content: flex-start;
        .msg-content {
          background-color: #fff;
        }
      }
    }
    &.right {
      .login-name,
      .avator {
        right: 0;
      }
      .msg-box {
        justify-content: flex-end;
        .msg-content {
          background-color: #9aee61;
        }
      }
    }
    .login-name {
      top: 0;
      height: $paddingT;
      line-height: $paddingT;
      font-size: px2(16);
    }
    .avator {
      top: $paddingT;
      width: px2(40);
      height: px2(40);
      border-radius: px2(6);
      overflow: hidden;
      img {
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        width: 100%;
      }
    }
    .msg-box {
      width: 100%;
      display: flex;
      .msg-content {
        padding: px2(10);
        font-size: px2(20);
        color: #333;
        line-height: px2(28);
        text-align: left;
        border-radius: px2(6);
      }
    }
  }
}

@media screen and (max-width: 992px) {
  .container {
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 100%;
    height: 100%;
  }
}
</style>
